package netty.io.demo.Netty.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;

public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler<HttpObject> {
  
  private static final byte[] CONTENT = "hello world".getBytes();
  
  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    // 从这里 表示 刷新结束
    ctx.flush();
  }
  
  // 这里执行 读处理
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
    if (httpObject instanceof HttpRequest) {
      HttpRequest req = (HttpRequest) httpObject;
      
      // 从这里 设置响应内容
      FullHttpResponse response = new DefaultFullHttpResponse(req.protocolVersion(), OK, Unpooled.wrappedBuffer(CONTENT));
      
      // 但是 这里设置headers
      response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN).setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
      
      // 从这里 写 response
      ctx.write(response);
    }
  }
}
